package de.hsowl.tod4a.global.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ZIPUnit {

	private static final int buffer = 8096;

	/**
	 * Decompression
	 * 
	 * @param compressedData
	 * @return
	 */
	public static synchronized byte[] unzip(byte[] compressedData) {
		try {
			// long time = System.currentTimeMillis();
			Inflater decompressor = new Inflater();
			decompressor.setInput(compressedData);

			ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

			byte[] buf = new byte[buffer];
			while (!decompressor.finished()) {
				int count = decompressor.inflate(buf);
				bos.write(buf, 0, count);
			}

			bos.close();

			return bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return compressedData;
	}

	/**
	 * Decompression
	 * @param compressedData
	 * @return
	 */
	public static synchronized String unzip(String compressedData) {
		return new String(unzip(compressedData.getBytes()));
	}

	/**
	 * Compression
	 * 
	 * @param input
	 * @return
	 */
	public static synchronized byte[] zip(byte[] uncompressedData) {
		// long time = System.currentTimeMillis();
		Deflater compressor = new Deflater();
		compressor.setLevel(Deflater.BEST_COMPRESSION);

		compressor.setInput(uncompressedData);
		compressor.finish();

		ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);

		byte[] buf = new byte[buffer];
		while (!compressor.finished()) {
			int count = compressor.deflate(buf);
			bos.write(buf, 0, count);
		}
		try {
			bos.close();
		} catch (IOException e) {
		}
		return bos.toByteArray();
	}

	/**
	 * Compression
	 * @param uncompressedData
	 * @return
	 */
	public static synchronized String zip(String uncompressedData) {
		return new String(zip(uncompressedData.getBytes()));
	}
}
